package com.example.bookkeep.Fragment;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.bookkeep.Mine.DataManageActivity;
import com.example.bookkeep.R;
import com.example.bookkeep.Utils.AuthUtil;
import com.example.bookkeep.Utils.URLUtils;
import com.example.bookkeep.login.LoginActivity;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class ProfileFragment extends Fragment {

    public ProfileFragment() {
        // Required empty public constructor
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_profile, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        // 示例用户信息（可替换为真实数据）
        TextView tvUsername = view.findViewById(R.id.tvUsername);
        TextView tvEmail = view.findViewById(R.id.tvEmail);
        ImageView ivAvatar = view.findViewById(R.id.ivProfileAvatar);
        Button btnLogout = view.findViewById(R.id.btnLogout);

        // 读取 token 和 userId
        String token = AuthUtil.getToken(getContext());
        int userId = AuthUtil.getUserId(getContext());

        System.out.println( "token ："+ token  + "userId : " + userId);


        if (token != null && userId != -1) {
            loadUserInfo(token, userId, tvUsername, tvEmail);
        }


//        tvUsername.setText("张三");
//        tvEmail.setText("zhangsan@example.com");
        ivAvatar.setImageResource(R.drawable.ic_user);  // 确保你有 ic_profile 资源

        // 设置每一项点击事件
        setClick(view, R.id.item_overview, "账本概述");
        setClick(view, R.id.item_chart, "图表统计");
        setClick(view, R.id.item_settings, "设置中心");
        setClick(view, R.id.item_data, "数据导出");
        setClick(view, R.id.item_security, "安全相关");
        setClick(view, R.id.item_about, "关于与反馈");

        btnLogout.setOnClickListener(v -> {
            // 清除登录状态，返回登录页
            Intent intent = new Intent(getContext(), LoginActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
            startActivity(intent);
        });
    }


    private void setClick(View view, int id, String title) {
        View item = view.findViewById(id);
        if (item != null) {
            item.setOnClickListener(v -> {
                if ("数据导出".equals(title)) {
                    Intent intent = new Intent(getContext(), DataManageActivity.class);
                    startActivity(intent);
                } else {
                    Toast.makeText(getContext(), title + " 被点击", Toast.LENGTH_SHORT).show();
                    // 可继续添加其他跳转逻辑
                }
            });


            // 设置图标和标题
            TextView tvTitle = item.findViewById(R.id.tvTitle);
            ImageView ivIcon = item.findViewById(R.id.ivIcon);
            if (tvTitle != null) {
                tvTitle.setText(title);
            }
            if (ivIcon != null) {
                switch (title) {
                    case "账本概述":
                        ivIcon.setImageResource(R.drawable.ic_account_book);
                        break;
                    case "图表统计":
                        ivIcon.setImageResource(R.drawable.ic_chart);
                        break;
                    case "设置中心":
                        ivIcon.setImageResource(R.drawable.ic_settings);
                        break;
                    case "数据管理":
                        ivIcon.setImageResource(R.drawable.ic_storage);
                        break;
                    case "安全相关":
                        ivIcon.setImageResource(R.drawable.ic_security);
                        break;
                    case "关于与反馈":
                        ivIcon.setImageResource(R.drawable.ic_feedback);
                        break;
                }
            }
        }
    }

    private void loadUserInfo(String token, int userId, TextView tvUsername, TextView tvEmail) {
        OkHttpClient client = new OkHttpClient();

        Request request = new Request.Builder()
                .url(URLUtils.BASE_URL + "/user/" +  userId)
                .addHeader("Authorization", "Bearer " + token)
                .get()
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                requireActivity().runOnUiThread(() ->
                        Toast.makeText(getContext(), "网络请求失败", Toast.LENGTH_SHORT).show());
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                if (response.isSuccessful()) {
                    String responseBody = response.body().string();

                    // 使用 fastjson 解析
                    JSONObject json = JSON.parseObject(responseBody);
                    int code = json.getInteger("code");
                    if (code == 1) {
                        JSONObject content = json.getJSONObject("content");
                        String username = content.getString("username");
                        String email = content.getString("email");

                        // 更新 UI 需要切回主线程
                        requireActivity().runOnUiThread(() -> {
                            tvUsername.setText(username);
                            tvEmail.setText(email);
                        });
                    } else {
                        String msg = json.getString("message");
                        requireActivity().runOnUiThread(() ->
                                Toast.makeText(getContext(), "获取失败: " + msg, Toast.LENGTH_SHORT).show());
                    }
                } else {
                    requireActivity().runOnUiThread(() ->
                            Toast.makeText(getContext(), "请求失败", Toast.LENGTH_SHORT).show());
                }
            }
        });
    }

}
